package cn.hw;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.io.*;

public class MainController {
    private TextArea currentTextArea=null;
    private int newNum = 1;

    @FXML
    private TabPane tabPane;
    @FXML
    private TextArea console;

    @FXML
    protected void quit(ActionEvent event){
        System.exit(0);
    }

    @FXML
    protected void newFile(ActionEvent event){
        String filename = "File"+newNum;
        newNum ++;
        newFile(filename,"",null);
    }
    private void newFile(String filename, String filepath, PlainDocument doc) {
        TextArea textArea = new TextArea();
        if (null != doc) {
            try {
                textArea.appendText(doc.getText(0, doc.getLength()));
                textArea.home();
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        }
        AnchorPane anchorpane = new AnchorPane();
        anchorpane.getChildren().add(textArea);
        AnchorPane.setBottomAnchor(textArea, 0.0);
        AnchorPane.setLeftAnchor(textArea, 0.0);
        AnchorPane.setRightAnchor(textArea, 0.0);
        AnchorPane.setTopAnchor(textArea, 0.0);
        Tab tab = new Tab();
        tab.setText(filename);
        tab.setContent(anchorpane);
        tab.getProperties().put("filename", filename);
        tab.getProperties().put("filepath", filepath);
        tab.setOnClosed(new EventHandler<Event>() {
            @Override
            public void handle(Event event) {
                String filepath1 = (String) tab.getProperties().get("filepath");
                System.out.println(filepath1);
            }
        });
        tabPane.getTabs().add(tab);
        tabPane.getSelectionModel().select(tab);

        tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {

            @Override
            public void changed(ObservableValue<? extends Tab> observable,
                                Tab oldValue, Tab newValue) {
                if(null == newValue)    return;//关闭窗口时为空
                AnchorPane panel = (AnchorPane) newValue.getContent();
                if (null != panel) {
                    TextArea textArea1 = (TextArea) panel.getChildren().get(0);
                    currentTextArea = textArea1;
                }


            }

        });
        currentTextArea = textArea;
    }

    @FXML
    protected void open(ActionEvent event){

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择文件");
        fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("Java Files", "*.java"));
        File selectedFile = fileChooser.showOpenDialog(null);
        if(null!=selectedFile){
            System.out.println("open file :"+selectedFile.getName());
            FileInputStream fis = null;
            BufferedReader in = null;
            PlainDocument doc = new PlainDocument();
            try {

                fis = new FileInputStream(selectedFile);
                in = new BufferedReader(new InputStreamReader(fis, "gbk"));//以特定编码格式读取文件
                char[] buff = new char[4096];
                int nch;
//                doc.removeDocumentListener(documentListener);
//                doc.removeUndoableEditListener(undoableEditListener);
                //已发现如果存在DocumentListener或者UndoableEditListener
                //在doc内监听的话,此时读取文件到doc将被阻塞,故先移除,等
                //操作结束后再加回来
                while ((nch = in.read(buff, 0, buff.length)) != -1) {
                    doc.insertString(doc.getLength(), new String(buff, 0, nch), null);

                }
                newFile(selectedFile.getName(),selectedFile.getCanonicalPath(), doc);
            } catch (BadLocationException e) {
                e.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
                in = null;
                fis = null;
            } finally {
                try {
                    in.close();
                    fis.close();
                } catch (Exception exc) {
                    exc.printStackTrace();
                }
//                doc.addDocumentListener(documentListener);
//                doc.addUndoableEditListener(undoableEditListener);
            }
        }

    }

    @FXML
    protected void save(ActionEvent event){
        Tab tab = tabPane.getSelectionModel().getSelectedItem();
        if(tab == null) return;
        String filename = tab.getText();
        AnchorPane node = (AnchorPane)tab.getContent();
        TextArea textArea = (TextArea)node.getChildren().get(0);
        String text = textArea.getText();
        String filepath = (String)tab.getProperties().get("filepath");
        if(null!=filepath&&!filepath.equals("")){
            File file = new File(filepath);
            try{
                FileOutputStream fos = new FileOutputStream(filepath);
                fos.write(text.getBytes());
                fos.close();
            }catch (IOException e){
                e.printStackTrace();
            }

        }else{
            FileChooser fileChooser = new FileChooser();
            fileChooser.setInitialFileName(filename+".java");
            File file = fileChooser.showSaveDialog(null);
            try {
                if(file == null)    return;//取消保存
                if(!file.exists()) file.createNewFile();
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(text.getBytes("gbk"));
                fos.close();
                tab.setText(file.getName());
                tab.getProperties().put("filename",file.getName());
                tab.getProperties().put("filepath",file.getCanonicalPath());
            }catch (IOException e){
                e.printStackTrace();
            }

        }
    }

    @FXML
    protected void othersave(ActionEvent event){
        Tab tab = tabPane.getSelectionModel().getSelectedItem();
        if(tab == null) return;
        AnchorPane node = (AnchorPane)tab.getContent();
        TextArea textArea = (TextArea)node.getChildren().get(0);
        String text = textArea.getText();

        FileChooser fileChooser = new FileChooser();
        fileChooser.setInitialFileName(".java");
        File file = fileChooser.showSaveDialog(null);
        try {
            if(file == null)    return;//取消保存
            if(!file.exists()) file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(text.getBytes("gbk"));
            fos.close();

            tab.getProperties().put("filename",file.getName());
            tab.getProperties().put("filepath",file.getCanonicalPath());

            tab.setText(file.getName());
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    @FXML
    protected void compile(ActionEvent event){
        Tab tab = tabPane.getSelectionModel().getSelectedItem();
        if(tab == null) return;
        String filepath = (String) tab.getProperties().get("filepath");
        String filename = (String) tab.getProperties().get("filename");
        if(null == filepath || filepath.equals("")) {
            new AlertBox().display("提示", "请先保存当前文档！","确定");
            return;
        }
        String cmd = "cmd /c javac -encoding gbk -verbose " + filepath;
        System.out.println(cmd);
        try{
            final Process process = Runtime.getRuntime().exec(cmd);
            printMessage(process.getInputStream());
            printMessage(process.getErrorStream());
            int value = process.waitFor();
            System.out.println(value);
        }catch (Exception e){
            System.out.println(111);
            e.printStackTrace();
        }

    }

    private void printMessage(final InputStream input) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Reader reader = new InputStreamReader(input,"gbk");
                    BufferedReader bf = new BufferedReader(reader);
                    String line = null;
                    while((line=bf.readLine())!=null) {
                        console.appendText(line+"\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @FXML
    protected void startRunning(ActionEvent event){
        Tab tab = tabPane.getSelectionModel().getSelectedItem();
        if(tab == null) return;
        String filepath = (String) tab.getProperties().get("filepath");
        String filename = (String) tab.getProperties().get("filename");
        if(null == filepath || filepath.equals("")) {
            new AlertBox().display("提示", "请先保存当前文档！","确定");
            return;
        }
        File classfile = new File(filepath.replace(".java",".class"));
        if(!classfile.exists()){
            new AlertBox().display("提示", "请先编译当前文档！","确定");
            return;
        }
        String cmd = "cmd /c java -classpath " + filepath.substring(0,filepath.lastIndexOf("\\")) + " " + filename.substring(0,filename.indexOf("."));
        System.out.println(cmd);
        try{
            final Process process = Runtime.getRuntime().exec(cmd);
            printMessage(process.getInputStream());
            printMessage(process.getErrorStream());
            int value = process.waitFor();
            System.out.println(value);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @FXML
    protected void help(ActionEvent event){
        new HelpView().start(new Stage());
    }

    @FXML
    protected void copyAction(ActionEvent event)
    {
        if(null!=currentTextArea)
        {
            this.currentTextArea.copy();
        }

    }
    @FXML
    protected void paseAction(ActionEvent event)
    {
        if(null!=currentTextArea)
        {
            this.currentTextArea.paste();
        }

    }
    @FXML
    protected void DeleteAction(ActionEvent event)
    {
        if(null!=currentTextArea)
        {
            this.currentTextArea.deleteText(this.currentTextArea.getSelection());
        }

    }
    @FXML
    protected void revokeAction(ActionEvent event)
    {
        if(null!=currentTextArea)
        {
            this.currentTextArea.undo();
        }
    }

}
